package org.example.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import org.example.reggie.entry.AddressBook;
import org.example.reggie.result.ResultData;
import org.example.reggie.service.AddressBookService;
import org.example.reggie.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.amqp.RabbitProperties;
import org.springframework.web.bind.annotation.*;
import org.yaml.snakeyaml.constructor.BaseConstructor;

import java.util.UUID;

/**
 * 地址管理 controller控制类
 */
@RestController
@RequestMapping("/addressBook")
public class AddressBookController {
    @Autowired
    private AddressBookService addressBookService;

    @PostMapping("/save")
    public ResultData<AddressBook> save(@RequestBody AddressBook addressBook){
        //当前用户id
        addressBook.setUserId((Long) ThreadLocalUtil.getMap().get("id"));
        addressBookService.save(addressBook);
        return ResultData.success(addressBook);
    }

    @PutMapping("/default")
    public ResultData<AddressBook>setDefault(@RequestBody AddressBook addressBook){
        LambdaUpdateWrapper<AddressBook> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(AddressBook::getUserId, (Long) ThreadLocalUtil.getMap().get("id"));
        wrapper.set(AddressBook::getIsDefault,0);
        addressBookService.update(wrapper);
        addressBook.setIsDefault(1);
        addressBookService.updateById(addressBook);
        return ResultData.success(addressBook);
    }

    @GetMapping("/{id}")
     public ResultData<AddressBook>getByid(@PathVariable Long id){
        AddressBook addressBook =  addressBookService.getById(id);
        if(null != addressBook){
            return ResultData.success(addressBook);
        }else{
            return ResultData.error("没有数据");
        }
    }

    @GetMapping("/defaultEntry")
    public ResultData<AddressBook>defaultEntry(@PathVariable Long id){
        LambdaQueryWrapper<AddressBook> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AddressBook::getUserId,(Long) ThreadLocalUtil.getMap().get("id"));
        queryWrapper.eq(AddressBook::getIsDefault,0);
        AddressBook addressBook =  addressBookService.getOne(queryWrapper);
        if(null != addressBook){
            return ResultData.success(addressBook);
        }else{
            return ResultData.error("没有数据");
        }
    }
}
